﻿# -*- coding: utf-8 -*-

from glob import glob
import os.path
import os
import sys
import sqlite3
import time

if len(sys.argv) < 3:
    print """
    Uso: user_rename.py usuario_antiguo usuario_nuevo
    
    Rename a user in all trac environments.
    
    """
    sys.exit(-1)

projects = glob(os.path.join(os.getcwd(), "*"))

old_user = sys.argv[1]
new_user = sys.argv[2]

tables = [
    ('attachment', 'author'),
    ('component', 'owner'),
    ('permission', 'username'),
    ('report', 'author'),
    ('ticket', 'owner'),
    ('ticket', 'reporter'),
    ('ticket_change', 'author'),
    ('wiki', 'author'),
]

for project in projects:
    db_file = os.path.join(project,"db", "trac.db")
    if os.path.exists(db_file):
        print "Renaming user in %s" % project
        print "-----------------------------------------------"
    else: 
        continue
    
    db = sqlite3.connect(db_file)
    
    for table, column in tables:
        print " Table %s column %s" % (table, column)
        db.execute("update %s set %s=? where %s=?" % (table, column, column), (new_user, old_user))

    db.commit()
    db.close()
